module key (
    input clk,
    input rst,
    input [3:0] key_row,
    output reg [3:0] key_col,
    output reg [3:0] val,
    output reg is_pressed
);

  reg [1:0] cnt;

  always @(posedge clk or negedge rst) begin
    if (!rst) begin
      cnt <= 2'd0;
    end else begin
      cnt <= cnt + 2'd1;
    end
  end

  always @(*) begin
    case (cnt)
      2'b00:   key_col = 4'b0111;
      2'b01:   key_col = 4'b1011;
      2'b10:   key_col = 4'b1101;
      2'b11:   key_col = 4'b1110;
      default: key_col = 4'b1111;
    endcase
  end

  always @(posedge clk or negedge rst) begin
    if (!rst) begin
      val <= 4'h0;
      is_pressed <= 1'b0;
    end else begin
      case ({
        key_col, key_row
      })
        8'b0111_0111: begin
          val <= 4'h1;
          is_pressed <= 1'b1;
        end
        8'b0111_1011: begin
          val <= 4'h2;
          is_pressed <= 1'b1;
        end
        8'b0111_1101: begin
          val <= 4'h3;
          is_pressed <= 1'b1;
        end
        8'b0111_1110: begin
          val <= 4'hA;
          is_pressed <= 1'b1;
        end

        8'b1011_0111: begin
          val <= 4'h4;
          is_pressed <= 1'b1;
        end
        8'b1011_1011: begin
          val <= 4'h5;
          is_pressed <= 1'b1;
        end
        8'b1011_1101: begin
          val <= 4'h6;
          is_pressed <= 1'b1;
        end
        8'b1011_1110: begin
          val <= 4'hB;
          is_pressed <= 1'b1;
        end

        8'b1101_0111: begin
          val <= 4'h7;
          is_pressed <= 1'b1;
        end
        8'b1101_1011: begin
          val <= 4'h8;
          is_pressed <= 1'b1;
        end
        8'b1101_1101: begin
          val <= 4'h9;
          is_pressed <= 1'b1;
        end
        8'b1101_1110: begin
          val <= 4'hC;
          is_pressed <= 1'b1;
        end

        8'b1110_0111: begin
          val <= 4'hE;
          is_pressed <= 1'b1;
        end
        8'b1110_1011: begin
          val <= 4'h0;
          is_pressed <= 1'b1;
        end
        8'b1110_1101: begin
          val <= 4'hF;
          is_pressed <= 1'b1;
        end
        8'b1110_1110: begin
          val <= 4'hD;
          is_pressed <= 1'b1;
        end

        default: begin
          val <= 4'h0;
          is_pressed <= 1'b0;
        end
      endcase
    end
  end

endmodule
